//
//  SerialRequestVC.swift
//  BWNetworkKit_Example
//
//  Created by zhuxuhong on 2022/3/21.
//  Copyright © 2022 CocoaPods. All rights reserved.
//

import BWUIKit
import BWToolKit
import BWNetworkKit
import BWHUDKit
import UIKit


class ImageCell: TableViewCell {
    @IBOutlet weak var iv: UIImageView!
    
    override func bwListItemViewConfigure(_ data: Any?, indexPath: IndexPath) {
        iv.image = data as? UIImage
    }
}

class SerialRequestsVC: TableViewController {
    override func didLoad() {
        super.didLoad()
        
        loadImages()
    }
    
    var images: [UIImage] = []
    
    let imageURLs: [URL] = {
        let prefix = "https://raw.githubusercontent.com/onevcat/Kingfisher-TestImages/master/DemoAppImage/HighResolution"
        return (1...20).map { URL(string: "\(prefix)/\($0).jpg")! }
    }()
    
    
    func reloadTableView(){
        listAdapter.data = .init(registers: [
        ], sections: [
            .init(items: images.map{
                .init(reuseId: ImageCell.RID, height: 400, data: $0, cellConfigure: nil, action: nil)
            })
        ])
    }
    
    var imageDownloadOperations: [GCD.Task.Operation] = []
    
    func loadImages()
    {
        imageDownloadOperations =
        Networker.send(
            requests: imageURLs.map{
                .init(host: .init(stringLiteral: $0.absoluteString))
            },
            queuePolicy: .serial,
            timeoutPolicy: .waiting
        ) { op in
            return .init {
                [weak self] state in
                    guard let self = self, self.isVisible else {
                       return
                   }
                   switch state {
                   case .loading:
                       HUD.loading()
                   case .failed(let error):
                       HUD.dismiss(all: .loading)
                       HUD.toast(error.localizedDescription)
                       op.completionBlock?()
                   case .success(let data):
                       guard let img = UIImage.init(data: data) else {
                           return
                       }
                       self.images.append(img)
                       let iv = UIImageView(image: img)
                       iv.contentMode = .scaleAspectFit
                       HUD.show(.square(.init(customView: iv, duration: 3, maskColor: .black)), completion: op.completionBlock)
                   case .finished:
                       HUD.dismissAll()
                   }
            } progressing: { progress, object in
                HUD.dismiss(all: .loading)
                HUD.progress(
                    .pie,
                    value: CGFloat(progress),
                    text:
    """
    \(Int(progress * 100))%\n
    \(object!.completedUnitCount.bw_bytesSized) / \(object!.totalUnitCount.bw_bytesSized)
    """
                )
            }
        } completion: { result in
            HUD.toast("\(result)")
        }
    }
    
    func cancelImageLoads(){
        imageDownloadOperations.forEach{op in
            if !op.isFinished {
                op.cancel()
            }
        }
    }
    
    override func willDisapppear() {
        cancelImageLoads()
    }
}

